// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const api = require('../../utils/api.js')

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    bannerList: [
      {
        id: 1,
        imageUrl: '/images/products/红玫瑰.png'
      },
      {
        id: 2,
        imageUrl: '/images/products/粉玫瑰.png'
      },
      {
        id: 3,
        imageUrl: '/images/products/蓝玫瑰.png'
      },
      {
        id: 4,
        imageUrl: '/images/products/香槟玫瑰.png'
      },
      {
        id: 5,
        imageUrl: '/images/products/碎冰蓝玫瑰.png'
      },
      {
        id: 6,
        imageUrl: '/images/products/粉色满天星.png'
      },
      {
        id: 7,
        imageUrl: '/images/products/香槟玫瑰白色满天星.png'
      }
    ],
    categories: [
      {
        id: 1,
        name: '鲜花',
        icon: '/images/icons/flower.png'
      },
      {
        id: 2,
        name: '绿植',
        icon: '/images/icons/plant.png'
      }
    ],
    recommendProducts: [
      {
        id: 1,
        name: '红玫瑰',
        price: 99,
        image: '/images/products/红玫瑰.png'
      },
      {
        id: 2,
        name: '粉玫瑰',
        price: 88,
        image: '/images/products/粉玫瑰.png'
      },
      {
        id: 3,
        name: '蓝玫瑰',
        price: 128,
        image: '/images/products/蓝玫瑰.png'
      },
      {
        id: 7,
        name: '香槟玫瑰白色满天星',
        price: 229,
        image: '/images/products/香槟玫瑰白色满天星.png'
      }
    ],
    hotProducts: [
      {
        id: 4,
        name: '香槟玫瑰',
        price: 108,
        image: '/images/products/香槟玫瑰.png'
      },
      {
        id: 5,
        name: '碎冰蓝玫瑰',
        price: 138,
        image: '/images/products/碎冰蓝玫瑰.png'
      },
      {
        id: 6,
        name: '粉色满天星',
        price: 79,
        image: '/images/products/粉色满天星.png'
      },
      {
        id: 7,
        name: '香槟玫瑰白色满天星',
        price: 229,
        image: '/images/products/香槟玫瑰白色满天星.png'
      }
    ],
    keyword: '',
    carouselList: [], // 轮播图列表
    recommendList: [], // 推荐商品列表
    hotList: [], // 热销商品列表
    loading: {
      carousel: true,
      recommend: true,
      hot: true
    }
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onLoad() {
    this.loadCarouselData()
    this.loadRecommendData()
    this.loadHotData()
  },
  // 输入搜索关键词
  onInput(e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  // 确认搜索
  onSearch() {
    const { keyword } = this.data;
    if (!keyword.trim()) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/search/search?keyword=${encodeURIComponent(keyword.trim())}`
    });
  },
  // 清空搜索
  clearSearch() {
    this.setData({
      keyword: ''
    });
  },
  // 点击分类
  onCategoryTap(e) {
    const id = e.currentTarget.dataset.id
    wx.switchTab({
      url: '/pages/category/category'
    })
  },
  // 轮播图点击事件
  onBannerTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/product/product?id=${id}&from=index`
    });
  },
  // 商品点击事件
  onProductTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/product/product?id=${id}&from=index`
    });
  },
  // 查看更多
  viewMore() {
    wx.switchTab({
      url: '/pages/category/category'
    })
  },
  // 跳转到商品详情页
  goToProduct(e) {
    const { id } = e.currentTarget.dataset;
    if (!id) {
      console.error('商品ID不存在');
      wx.showToast({
        title: '商品信息错误',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    console.log('跳转到商品详情，ID:', id);
    wx.navigateTo({
      url: `/pages/product/product?id=${id}&from=index`
    });
  },
  // 跳转到搜索页
  goToSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  // 跳转到分类页
  goToCategory() {
    wx.switchTab({
      url: '/pages/category/category'
    })
  },
  // 下拉刷新
  async onPullDownRefresh() {
    try {
      await Promise.all([
        this.loadCarouselData(),
        this.loadRecommendData(),
        this.loadHotData()
      ])
    } finally {
      wx.stopPullDownRefresh()
    }
  },
  // 加载轮播图数据
  async loadCarouselData() {
    try {
      const res = await api.getCarouselProducts()
      if (res.success) {
        this.setData({
          carouselList: res.data,
          'loading.carousel': false
        })
      } else {
        wx.showToast({
          title: res.message || '加载轮播图失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载轮播图失败:', error)
      wx.showToast({
        title: '加载轮播图失败',
        icon: 'none'
      })
    } finally {
      this.setData({
        'loading.carousel': false
      })
    }
  },
  // 加载推荐商品数据
  async loadRecommendData() {
    try {
      const res = await api.getRecommendProducts({ page: 1, size: 6 })
      if (res.success) {
        this.setData({
          recommendList: res.data.content,
          'loading.recommend': false
        })
      } else {
        wx.showToast({
          title: res.message || '加载推荐商品失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载推荐商品失败:', error)
      wx.showToast({
        title: '加载推荐商品失败',
        icon: 'none'
      })
    } finally {
      this.setData({
        'loading.recommend': false
      })
    }
  },
  // 加载热销商品数据
  async loadHotData() {
    try {
      const res = await api.getHotProducts({ page: 1, size: 6 })
      if (res.success) {
        this.setData({
          hotList: res.data.content,
          'loading.hot': false
        })
      } else {
        wx.showToast({
          title: res.message || '加载热销商品失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载热销商品失败:', error)
      wx.showToast({
        title: '加载热销商品失败',
        icon: 'none'
      })
    } finally {
      this.setData({
        'loading.hot': false
      })
    }
  }
})
